﻿var post_url='/attendance/ajax/';
var app = angular.module('he',['ui.router','ngSanitize','ngStorage']);
app.run(function($rootScope){
	$rootScope.static_url=static_url;
})
//[设置app的取值符号]从{{  }}改为[[ ]]
app.config(function($interpolateProvider) {
	  $interpolateProvider.startSymbol('[[');
	  $interpolateProvider.endSymbol(']]');
	});

//[动态注册angularjs的组件]
app.config(function($controllerProvider,$compileProvider,$filterProvider,$provide){
    app.register =
        {
            controller: $controllerProvider.register,
            directive: $compileProvider.directive,
            filter: $filterProvider.register,
            factory: $provide.factory,
            service: $provide.service
        };
});

//[从start处开始截取input数组]
app.filter('offset', function() { 
	return function(input, start) {
		start = parseInt(start,10);
		return input.slice(start) 
		}
})


//[生成dom元素时，自动获得焦点]
app.directive('autoFocus', function($timeout) {
    return {
        restrict: 'A',
        link: function(_scope, _element) {
            $timeout(function(){
                _element[0].focus();
            }, 10);
        }
    };
});
//[tabel中的文字单元]
app.directive('textCell',function () {
	return {
		restrict:'A',
		scope:{
			model:'=',
		},
		template:"<td  ng-dblclick='editor.show=true'>\
		          <span ng-bind='model' ng-if='!editor.show'></span>\
		          <span ng-if='editor.show'>\
			      <input auto-focus type='text' name='ggg' ng-model='$parent.model' ng-blur='editor.show=false'/>\
			       </span>\
	               </td>"
	}
})
//---
app.directive('editText',function () {
	// <span db-text model='record.end_time' dirty='record.end_time_dirty' width='80px' pattern='^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$'></span>
	return {
		restrict:'A',
		scope:{
			model:'=',
			makedirty:'&',
			showEditor:'='
		},
		template:"<span '>\
		          <span ng-bind='model' ng-show='!showEditor' ng-click='wn_click()'></span>\
		          <span ng-if='showEditor'>\
			      <input ng-class='is_valid' style='[[style]];outline:0 none' auto-focus type='text' name='ggg' ng-model='$parent.selfmodel' ng-blur='on_blur()'/>\
			       </span>\
	              </span>",
	    link:function (scope,ele,attr) {
		    scope.wn_click=function () {
		    	if(typeof attr.showEditor=='undefined'){
			    	scope.showEditor=true;
		    	}
		    }
		    if(attr.width){
			    scope.style='width:'+attr.width;
		    }else{
			    scope.style=''
		    }
		    scope.on_blur=function () {
		    	scope.showEditor=false;
		    	scope.selfmodel=scope.model;
		    }
		    scope.selfmodel=scope.model;
	    	scope.$watch('selfmodel',function (newval,oleval) {
		    	if(typeof scope.makedirty == "undefined"){
			    	// 初始化时运行这里
			    	scope.makedirty=function () {
			    	};
			    	return
		    	}
	
		    	if(attr.pattern){
			    	var pt =new RegExp(attr.pattern);
			    	if(pt.test(newval)){
				    	if(scope.model!=newval){
					    	//scope.dirty=true;
					    	scope.makedirty();
				    	}
				    	scope.model=newval;
				    	scope.is_valid=''
			    	}else{
				    	scope.is_valid='input-invalid'
			    	}
		    	}else{
			    	if(scope.model!=newval){
					    //scope.dirty=true;
					    	scope.makedirty();
				    	}
			    	scope.model=newval;
			    	scope.is_valid=''
		    	}
	    	})
	    }
	}
})
// table的selectCell;参数，model:绑定的值，choices:[{value:'approved',label:'同意'},{value:'rejected',label:'拒绝'}]
app.directive('selectCell',function () {
	return {
		restrict:'A',
		scope:{
			model:'=',
			choices:'=',
			//wraper_click:'&'
		},
		template:"<td ng-dblclick='editor.show=true'>\
		          <span ng-bind='model' ng-show='!editor.show'></span>\
		          <span ng-if='editor.show' ng-click='$event.stopPropagation()'>\
			      <select name='hh' ng-model='$parent.model' auto-focus ng-change='editor.show=false'>\
			       	<option value='[[choice.value]]' ng-repeat='choice in choices' >[[choice.label]]</option>\
		           </select>\
		           </span>\
	              </td>",
	    link:function (scope, ele, attr) {
		    scope.editor={show:false}
			$( "body" ).click(function() {
				if(scope.editor.show){
					scope.$apply(function () {
					scope.editor.show=false;
				})}
			});
	    }
	              
	} 
})

app.directive('simSelect',function () {
//<span sim-select model='report.category' dirty='report.category_dirty' choices='[{name:"annual_leave",value:"annual_leave"},{name:"swap_off",value:"swap_off"}]' ></span>
	// choices=[{name:'dog',value:'dog'}]
	return {
		restrict:'A',
		scope:{
			model:'=',
			choices:'=',
			makedirty:'&',
		},
		template:"<span style='position: relative;' ng-click='editor.show=!editor.show;$event.stopPropagation()'>\
				   <span ng-bind='label_it(model)'></span>\
			        <ul ng-if='editor.show' class='pop_option'>\
				     <li ng-bind='choice.name' ng-repeat='choice in choices' ng-click='liclick(choice,$event)'></li>\
			         </ul>\
			      </span>",
	    link:function (scope, ele, attr) {
		    scope.editor={show:false}
		    if(typeof scope.makedirty=='undefined'){
			    scope.makedirty=function () {//空函数
			    }
		    }
			$( "body" ).click(function() {
				if(scope.editor.show){
					scope.$apply(function () {
					scope.editor.show=false;
				})}
			});
	    },
	    controller:function ($scope) {
		    $scope.label_it=function (model) {
		    	for(x in $scope.choices){
			    	if($scope.choices[x].value==model){
				    	return $scope.choices[x].name
			    	}
		    	}
		    	return model
		    }
	    	$scope.liclick=function (choice,event) {
		    	if(choice.value!=$scope.model){
			    	$scope.makedirty()//=true;
		    	}
	    		$scope.model=choice.value;
				$scope.editor.show=false;
		    	event.stopPropagation()
		    	
	    	}
	    }
	              
	} 
})

app.directive('mySelect',function ($timeout) {
	return {
		restrict:'A',
		scope:{
			model:'=',
			label:'=',
			choices:'=',
			update:'&'
		},
		template:"<span style='position: relative;' ng-click='editor.show=true;$event.stopPropagation()'>\
				      <span ng-bind='label'></span>\
			           <ul ng-if='editor.show' class='cell_option'>\
				          <li ng-bind='choice' ng-repeat='choice in choices' ng-click='liclick(choice,$event)' style='list-style-type: none;'></li>\
			           </ul>\
			      </span>",

	    link:function (scope, ele, attr) {
		    scope.editor={show:false}
			$( "body" ).click(function() {
				if(scope.editor.show){
					scope.$apply(function () {
					scope.editor.show=false;
				})}
			});
	    },
	    controller:function ($scope) {
	    	$scope.liclick=function (choice,event) {
	    		$scope.model=choice;
				$scope.editor.show=false;
		    	event.stopPropagation()
		    	$timeout(function () {
		    		$scope.update();
		    	})
	    	}
	    }
	              
	} 
})

app.directive('sortMark',function () {
	//<span sort-mark name='field.name' items='records'></span>
	return {
		restrict :'A',
		replace:true,
		transclude:true,
		scope:{
			items:'=',
			name:'=',
			rt:'='
		},
		template:"<span ng-click='sort()' class='sort-head'>\
				<span ng-class='{\"low\":!is_sort()}' ng-show='positive||!is_sort()' class='fa fa-caret-up'></span>\
				<span ng-class='{\"low\":!is_sort()}' ng-show='!positive||!is_sort()' class='fa fa-caret-down'></span><span ng-transclude></span></span>",
		controller:function ($scope) {
			if(typeof $scope.items =='undefined'){
				$scope.items=[];
			}
			$scope.is_sort=function () {
				if(typeof $scope.items.crt_name!='undefined'){
					return $scope.items.crt_name==$scope.name
				}else{
					return false;
				}
			};
			$scope.sort=function () {
				// 排序表格
				$scope.items.crt_name=$scope.name
				if($scope.positive){
					$scope.positive=false;
				}else{
					$scope.positive=true;
				}
				
				//$scope.items=$filter('orderBy')($scope.items, prefix+$scope.name)
				$scope.items.sort(function (a,b) {
					var rt;
					if (a[$scope.name]>b[$scope.name]){
							rt= 1
						}else if(a[$scope.name]<b[$scope.name]){
							rt= -1
						}else{
							rt= 0
						}
						
					if ($scope.positive){
						return rt
					}else{
						return -rt
					}
				})
		   }
		}
		
	}
})

// 页面的角标，输入参数：per:每页数量,crt：当前页编号，items:数组
// 之所以传入items，而不适items.length，是因为items.length可能会发生变化
app.directive('pageFoot',function () {
	return {
		restrict :'A',
		scope:{
			itemsPerPage:'=per',
			currentPage:'=crt',
			items:'='
		},
		template:"<ul class='pagination'>\
				<li ng-class='prevPageDisabled()'>\
					<a href ng-click='prevPage()'>Prev</a>\
				</li>\
				<li ng-repeat='n in range()' ng-class='{active: n == currentPage}' ng-click='setPage(n)'>\
					<a href='' ng-bind='n+1'></a> </li>\
				<li ng-class='nextPageDisabled()'>\
					<a href ng-click='nextPage()'>Next</a>\
				</li> \
			</ul>",
	
	link:function (scope, ele, attr) {
		//if (angular.isUndefined(scope.allowSomething))
  //      $scope.allowSomething = true;
  
   // 		scope.itemsPerPage = 57;
			//scope.currentPage = 0;
			//scope.items = items
  			scope.prevPage = function() { 
			if (scope.currentPage > 0) {scope.currentPage-- }
			};


			scope.prevPageDisabled = function() {
				return scope.currentPage === 0 ? "disabled" : "";
			};

			scope.pageCount = function() {
				return Math.ceil(scope.items.length/scope.itemsPerPage)-1;
			};
			scope.range=function () {
				var out=[];
				var length=scope.pageCount();
				for(var x =0;x<=length;x++){
					out.push(x)
				}
				return out
			}
			scope.setPage=function (n) {
				scope.currentPage=n;
			}
			scope.nextPage = function() {
			if (scope.currentPage < scope.pageCount()) {
				scope.currentPage++;
				}
			};

			scope.nextPageDisabled = function() {
				return scope.currentPage === scope.pageCount() ? "disabled" : "";
			}
	}
}
})
// 按照order数组里面的循序，排列inputArray:[{name:'one'},{name:'two'}]的顺序
app.filter('orderList',function(){
    return function(inputArray,order){
        var array = [];
        for (x in order){
	        for(y in inputArray){
		        if (inputArray[y].name==order[x]){
			        array.push(inputArray[y])
		        }
	        }
        }
        return array;
    }
});

app.directive("fileread", [function () {
    return {
        scope: {
            fileread: "="
        },
        link: function (scope, element, attributes) {
            element.bind("change", function (changeEvent) {
                var reader = new FileReader();
                reader.onload = function (loadEvent) {
                    scope.$apply(function () {
                        scope.fileread = loadEvent.target.result;
                    });
                }
                reader.readAsBinaryString(changeEvent.target.files[0]);
            });
        }
}}
]);
// 
app.factory('file',function ($http) {
	return {
		upload:function (fd,url) {
    		return $http.post(url,fd,{
	                  transformRequest: angular.identity,
	                  headers: {'Content-Type': undefined}
	            })
    		}
	}
})
// 文件加载
app.directive("fileload", function () {
    return {
        scope: {
            model:'=',
        },
        link: function (scope, element, attributes) {
            element.bind("change", function (changeEvent) {
                var fd = new FormData();
                file=changeEvent.target.files[0]
   				fd.append('file', file);
   				scope.$apply(function () {
   					scope.model=fd;
   				})
            });
        }
}})


//--------------上传文件的 input 和button-----------------------------------------------------
// 例子：
//   <div file-input com='attend_record' accept='.xls'></div>
//	 <div file-btn com='attend_record' label='提交考勤记录' url='/attendance/upload/'></div>
//
app.directive('fileInput',function () {
	return {
		restrict :'A',
		//replace:true,
		scope:{
			com:'=',
		},
		template:"<span><input fileload model='com' type='file' accept='[[accept]]'></span>",
		link:function (scope,ele,att) {
			scope.accept=att.accept;
			
		}
	}
});

app.directive('fileBtn',function (file) {
	// 文件提交按钮，必须和fileInput一起使用,
	return {
		restrict :'A',
		replace: true,
		scope:{
			//label:'=',
			//url:'=',
			filebody:'=com'
		},
		template:"<span><button  type='button'  ng-click='upload_file()' ng-disabled='!filebody||uploading'><span ng-bind='label'></span></button><span class='fa fa-spinner fa-spin' ng-show='uploading'></span><span>",
		controller:function ($scope) {
				$scope.upload_file=function () {
					if(!$scope.filebody){
						alert('not load over');
						return
					}
					$scope.uploading=true;
					file.upload($scope.filebody,$scope.url)
					.success(function (data) {
						$scope.uploading=false;
						alert(data.status)
					} ).error(function () {
						alert('has erroe')
					})
				}
		},
		link:function (scope,ele,attr) {
			scope.uploading=false;
			scope.label=attr.label;
			scope.url=attr.url;
		}
	}
})

app.directive('getExcel',function ($http) {
	// <span get-excel data='reports' heads='heads' url='/attendance/getexcel/' class="fa fa-sort-amount-desc toolbtn"></span>
	// heads: 表格的头
	// data: 表格的Array
	return {
		restrict :'A',
		replace:true,
		scope:{
			data:'=',
			heads:'='
		},
		template:"<span ng-click='get_excel_from_server()'></span>",
		link:function (scope,ele,attr) {
			scope.url=attr.url
			scope.get_excel_from_server=function (data,url) {
				post(scope.url,{data:scope.data,heads:scope.heads})
			
			}
			
			
		}
	}
})
//----------------------------------------------------------------------
app.directive('fileLoader',function ($http) {
	// accept
	return {
		restrict :'A',
		replace:true,
		scope:{
			//onload:'&',
			var:'='
		},
		template:"<input model='filebody' type='file'>",
		link:function (scope,ele,attr) {
			scope.var={	name:'',
						uploading:false};
			
			ele.bind("change", function (changeEvent) {
                var fd = new FormData();
                file=changeEvent.target.files[0]
   				fd.append('file', file);
   				scope.$apply(function () {
   					scope.filebody=fd;
   					scope.var.name=file.name;
   					//scope.onload();
   					if(attr.onload){
	   					scope.$parent.$eval(attr.onload)
   					}
   				})
            });
            scope.var.upload=function (url) {
	            scope.var.uploading=true;
	    		rt= $http.post(url,scope.filebody,{
		                  transformRequest: angular.identity,
		                  headers: {'Content-Type': undefined}
	            })
	            rt.success(function () {
	            	scope.var.uploading=false;
	            })
	            return rt
    		}
		},
	}
});
//------------------------------------------------------------
//app.directive('btnFile',function () {
//	return {
//		restrict :'A',
//		replace: true,
//		transclude: 'true',
//		scope:{
//			filename:'='
//		},
//		template:"<div class='btn-file'>\
//				<span ng-transclude class='hidden-input'></span>\
//			   <span ng-hide='filename' ng-bind='label'></span>\
//			   <span ng-bind='filename'></span>\
//		   </div>",
//		link:function (scope,ele,attr) {
//			scope.label=attr.label
//		},
//		controller:function ($scope) {
//			$scope.$watch('filename',function (n,o) {
//				alert(n);
//			})
//		}
//	}
			 
//})

// <span file-loader var='myfile' class='hidden-input'></span>\